# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd

def return_data(data):
    '''
    返回 5 个异常时刻，以及时刻下 5 个最异常的感应器
    '''
    data_sum = data.sum(axis=0)
    idx_list = []
    score = []
    for i in range(1, 6):
        data_sort = np.sort(data_sum)[-i]
        idx = np.where(data_sum == data_sort)
        idx_list.append(idx[0][0])
        # 分数
        score.append(data_sort)
        
    data_select = data.iloc[:, idx_list]
    sensor_list = {}
    sensor_name = data_select.index
    for i in range(5):
        # 5 个时刻
        tmp = data_select.iloc[:, i]
        sensor_list_period = []
        for j in range(1, 6):
            # 5 个感应器
            data_sort = np.sort(tmp)[-j]
            if data_sort >= 0.99 and data_sort <= 1.01:
                continue
            idx = np.where(tmp == data_sort)[0][0]
            tmp[idx] = 0
            sensor_worst = sensor_name[idx]
            sensor_list_period.append(sensor_worst)
        
        sensor_list_period.append(score[i])
        sensor_list[idx_list[i]] = sensor_list_period
    
    return sensor_list

def print_result(sensor_list):
    '''
    打印结果
    '''
    time = pd.timedelta_range(start='0 hour', periods=46, freq='0.5H')
    
    for k,v in sensor_list.items():
        t_idx = time[k]
        print(f'当前时刻为：{t_idx}')
        print('异常的感应器有： ', v[:-1])
        print('异常得分为： ', v[-1], '\n')
if __name__ == '__main__':
    path = r'../附件/中间数据/时间-风险.xlsx'
    data = pd.read_excel(path, index_col=0, header=0)
    sensor_list = return_data(data)
    print_result(sensor_list)